# -*- coding: utf-8 -*-
# @Time    :2022/1/12 23:06
# @AUTHOR  :MORAN
# @Email   :moran@maqu.com
# @File    :serializers.py
# @Software:PyCharm
import re

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from django.contrib.auth.models import User

from users.models import UserDetail, Area, Address


class UserDetailSerializer(ModelSerializer):
    class Meta:
        model = UserDetail
        fields = '__all__'
        extra_kwargs = {
            'avatar': {'read_only': True},
            'user': {'write_only': True}
        }


class UserSerializer(ModelSerializer):
    userdetail = UserDetailSerializer(required=False, read_only=True)

    class Meta:
        model = User
        exclude = ['password', 'last_name', 'user_permissions']

        extra_kwargs = {
            'last_login': {'read_only': True},
            'is_superuser': {'read_only': True},
            'is_staff': {'read_only': True},
            'is_active': {'read_only': True},
            'date_joined': {'read_only': True},
            'groups': {'read_only': True}
        }


class CreateUserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }


class AreaSerializer(ModelSerializer):
    class Meta:
        model = Area
        fields = ['id', 'name']


class ParentSerializer(ModelSerializer):
    area_set = AreaSerializer(many=True, read_only=True)

    class Meta:
        model = Area
        fields = ['id', 'name', 'area_set']


class AddressSerializer(ModelSerializer):
    class Meta:
        model = Address
        exclude = ['is_delete']

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号码格式错误')
        return value
